package com.lingnan.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lingnan.mapper.ActiveMapper;
import com.lingnan.mapper.ReceiveMapper;
import com.lingnan.mapper.TargetMapper;
import com.lingnan.pojo.*;
import com.lingnan.mapper.UserMapper;
import com.lingnan.service.ActiveService;
import com.lingnan.service.TargetService;
import com.lingnan.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingnan.util.HttpRequestUtil;
import com.lingnan.util.MD5Utils;
import com.lingnan.util.ResultGenerator;
import com.lingnan.vo.UserVo;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 梁兴达
 * @since 2022-03-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private ActiveService activeService;
    @Autowired
    private ActiveMapper activeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TargetService targetService;

    @Autowired
    private TargetMapper targetMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ReceiveMapper receiveMapper;

    @Override
    public User login(UserVo userVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("no",userVo.getNo());
        wrapper.eq("password",MD5Utils.MD5Encode(userVo.getPassword(),"UTF-8"));
        User one = getOne(wrapper);

        if (one != null){
            return one;
        }
        return null;
    }

    @Override
    public User getByNo(String no) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("no",no);
        User one = getOne(wrapper);
        if (one != null){
            return one;
        }
        return null;
    }

    @Override
    public boolean register(UserVo userVo) {
//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("no",userVo.getNo());
//        hashMap.put("name",userVo.getName());
//        hashMap.put("password",userVo.getPassword());
//        HashMap<String, String> map1 = new HashMap<>();
//        map1.put("no",userVo.getNo());
//        map1.put("email",userVo.getEmail());
//        ResponseEntity<JSONObject> post = HttpRequestUtil.
//                httpRequestByMapAndUrlAndmethod(hashMap, "http://120.77.247.146:1281/student", "post", restTemplate);
//
//        ResponseEntity<JSONObject> email = HttpRequestUtil.
//                httpRequestByMapAndUrlAndmethod(map1, "http://120.77.247.146:1281/band-email", "post", restTemplate);
//
//        JSONObject body = post.getBody();
//        JSONObject postBody =email.getBody();
//        HttpStatus statusCode = post.getStatusCode();
//        int value = statusCode.value();
//        //Map mapEmail = (Map) (postBody != null ? postBody.get("data") : null);
//        Map emailResult = (Map)(postBody != null ? postBody.get("data") : null);
//        String no = (String) (emailResult != null ? emailResult.get("no") : null);
//        Map map = (Map) (body != null ? body.get("data") : null);
//        String no1 = (String) (map != null ? map.get("no") : null);
//        if (userVo.getNo().equals(no)){
//            if (statusCode.value()==value&&userVo.getNo().equals(no1)){
        if (!ObjectUtils.isEmpty(userVo)){
                User user = new User();
                user.setNo(userVo.getNo());
                user.setPassword(MD5Utils.MD5Encode(userVo.getPassword(),"UTF-8"));
                user.setName(userVo.getName());
                user.setGender(userVo.getGender());
                user.setPhone(userVo.getPhone());
                user.setEmail(userVo.getEmail());
                user.setCreateTime(userVo.getCreateTime());
                userMapper.insert(user);
//                return body;
            return true;
            }
            return false;

    }

    @Override
    public List<Active> noticesList(String no) {
        ConcurrentHashMap<String, Object> hashMap = new ConcurrentHashMap<>();
        // 查询出来这个学生的所有活动
        // via student no => grade + school + major like
        System.out.println(no);
        hashMap.put("grade", no.substring(0, 4));
        hashMap.put("school_id", Integer.valueOf(no.substring(4, 6)));
        hashMap.put("major_id", no.substring(6, 8));
        List<Target> targets = targetMapper.selectByMap(hashMap);
        // 获取到了所有以这个学生为对象的活动（获得所有活动active）
        ArrayList<Integer> integers = new ArrayList<>();
        for (int i = 0; i < targets.size(); i++) {
            integers.add(targets.get(i).getActiveId());
        }
        ArrayList<Active> actives1 = new ArrayList<>();
        //ArrayList<Active> actives2 = new ArrayList<>();
        //获得了所有的active
        integers.stream().forEach(e -> {
            QueryWrapper<Active> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",e);
            queryWrapper.in("info_type","紧急通知(需回复)","紧急通知(勿回复)");
            List<Active> activeList = activeMapper.selectList(queryWrapper);
            if (activeList.size() > 0){
                Active active = activeList.get(0);
                actives1.add(active);
            }
        });
//        for (Active active : actives1) {
//            QueryWrapper<Receive> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("no", no).eq("info_id", active.getId());
//            Receive receive = receiveMapper.selectOne(queryWrapper);
//            //如果这个活动在签到表中存在，则设置为已经签到
//            if (!ObjectUtils.isNull(receive)){
//                active.setIsReceive(1);
//            }
//        }
//        integers.stream().forEach(e -> {
//            QueryWrapper<Active> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("id",e);
//            queryWrapper.in("info_type","紧急通知(需回复)","紧急通知(勿回复)");
//            List<Active> activeList = activeMapper.selectList(queryWrapper);
//            if (activeList.size() > 0){
//                Active active = activeList.get(0);
//                actives2.add(active);
//            }
//        });
        return actives1;
    }



    @Override
    public List<Active> activesTodayList(String no) {
        ConcurrentHashMap<String, Object> hashMap = new ConcurrentHashMap<>();
        // 查询出来这个学生的所有活动
        // via student no => grade + school + major like
        System.out.println(no);
        hashMap.put("grade", no.substring(0, 4));
        hashMap.put("school_id", Integer.valueOf(no.substring(4, 6)));
        hashMap.put("major_id", no.substring(6, 8));
        List<Target> targets = targetMapper.selectByMap(hashMap);
        // 获取到了所有以这个学生为对象的活动（获得所有活动active）
        ArrayList<Integer> integers = new ArrayList<>();
        for (int i = 0; i < targets.size(); i++) {
            integers.add(targets.get(i).getActiveId());
        }
        ArrayList<Active> actives1 = new ArrayList<>();
        //ArrayList<Active> actives2 = new ArrayList<>();
        //获得了所有的activeId

        LocalDate now = LocalDate.now();
        integers.stream().forEach(e -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",e);
            map.put("info_type","非通知");
            map.put("begin_time",now);
            List<Active> actives = activeMapper.selectByMap(map);
            if (actives.size() > 0){
                Active active = actives.get(0);
                actives1.add(active);
            }
        });
        return actives1;
    }

    @Override
    public User reSetPassword(UserVo userVo) {
//        HashMap<String, String> map = new HashMap<>();
//        map.put("email",userVo.getEmail());
//        ResponseEntity<JSONObject> result = HttpRequestUtil.
//                httpRequestByMapAndUrlAndmethod(map, "http://120.77.247.146:1281/send-verification", "get", restTemplate);
//        JSONObject postBody =result.getBody();
//        String emailResult = (String)(postBody != null ? postBody.get("data") : null);

        HashMap<String, Object> map1 = new HashMap<>();
//        ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>();
            map1.put("no",userVo.getNo());
            map1.put("email",userVo.getEmail());
//            hashMap.put("no",userVo.getNo());
//            hashMap.put("password",userVo.getPassword());
//        ResponseEntity<JSONObject> result = HttpRequestUtil.
//                reSetPassword(hashMap, "http://120.77.247.146:1281/modify-password", restTemplate);
//        JSONObject body = result.getBody();

        List<User> users = userMapper.selectByMap(map1);
            if (!ObjectUtils.isEmpty(users)){
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("no",userVo.getNo())
                .eq("email",userVo.getEmail());
                User user = users.get(0).setPassword(userVo.getPassword());
                userMapper.update(user, updateWrapper);

            }
        return users.get(0);
    }

    @Override
    public JSONObject getEmailCode(String email) {
        HashMap<String, String> map = new HashMap<>();
        map.put("email",email);
        ResponseEntity<JSONObject> result = HttpRequestUtil.
                httpRequestByMapAndUrlAndmethod(map, "http://120.77.247.146:1281/send-verification", "get", restTemplate);
        JSONObject postBody =result.getBody();
        String emailResult = (String)(postBody != null ? postBody.get("data") : null);
        return postBody;
    }
}
